'''Title  : GoogleQuote
   Version: 0.9
   Author : Glenn Y. Chen
   Summary: Check Stock Quote with Google Finance
   License: FreeBSD 
'''

import urllib    
import StringIO
import sys

def stream(contents):
    stream = StringIO.StringIO(contents)
    for line in stream:
	if line.startswith('<span class="pr"'):
            start = line.find('>')+1
            end   = line.rfind('</sp')
            return line[start:end]
    print 'oops, need code change~quote not found'

def getHtmlSource(symbol):   
    sock = urllib.urlopen("http://finance.google.com/finance?q="+symbol) 
    htmlSource = sock.read()
    sock.close()  
    return stream(htmlSource)

def getTaiwanQuote(number):
    sock = urllib.urlopen("http://tw.stock.yahoo.com/q/q?s="+number)
    htmlSource = sock.read()
    sock.close()
    return streamTaiwan(htmlSource)

def streamTaiwan(contents):
    stream = StringIO.StringIO(contents)
    for line in stream:
        targetLine =  '<td align="center" bgcolor="#FFFfff" nowrap>'
        if (line.lstrip()).startswith(targetLine):
            line = stream.readline()
            start = line.find('b>')+2
            end   = line.rfind('</b')
            return line[start:end]
    print 'oops, need code change~quote not found'

def hexCheck(string):
    return string.encode("hex") > "39393939".encode("hex")

def usage():
    print 'usage:'
    print 'python googlequote.py [symbol | ... ]'
    print 
    print '(you will be rich one day)'


if __name__ == "__main__":
    if len(sys.argv) < 2:
       usage()

    for arg in sys.argv[1:]:
	if hexCheck(arg):
            print arg.upper()+' '+getHtmlSource(arg)	    
        else:
            print arg+' '+getTaiwanQuote(arg)
